/**
 * Copyright &copy; 2018-2018 <a href="#">聚成科技</a> All rights reserved.
 */
package com.jckj.core.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.jckj.core.contants.SysContants;
import com.jckj.core.entity.SysAttachment;
import com.jckj.core.entity.SysUser;
import com.jckj.core.service.SysAttachmentService;
import com.jckj.core.service.UserService;
import com.jckj.core.util.FileUploadUtils;
import com.jckj.core.util.FileUtils;
import com.jckj.core.util.StringUtils;
import com.jckj.core.vos.LoginUserVo;
import com.jckj.core.vos.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * <p>
 *    通知控制器
 * </p>
 *
 * @author 刘志远
 * @date 18-1-23
 */
@Controller
@RequestMapping("/common")
public class CommonController{

    private final static Logger LOGGER = LoggerFactory.getLogger(CommonController.class);

    /**
     * 验证码
     */
    @Autowired
    DefaultKaptcha kaptcha;

    @Autowired
    private LoginUserVo loginUserVo;

    @Autowired
    SysAttachmentService sysAttachmentService;

    @Autowired
    UserService userService;

    /**
     * 上传文件
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload", method= RequestMethod.POST)
    @ResponseBody
    public Result upload(@RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request){
        String path = request.getSession().getServletContext().getRealPath("/") + File.separator + SysContants.FILE_UPLOAD_LOCATION;
        String fileName = file.getOriginalFilename();
        String newFileName = FileUtils.getNewFileName(fileName);
        final File targetFile = new File(path, newFileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        String id = StringUtils.genId();
        final String remoteFileName  = SysContants.FILE_UPLOAD_PREFIX + id + FileUtils.getFileExt(fileName);
        //保存
        try {
            file.transferTo(targetFile);
            //异步上传到远程服务器
            new Thread(new Runnable() {
                @Override
                public void run() {
                    FileUploadUtils.uploadFile(targetFile, remoteFileName);
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        SysAttachment sysAttachment = new SysAttachment();
        sysAttachment.setId(id);
        sysAttachment.setFileName(fileName);
        sysAttachment.setRemoteFilePath(remoteFileName);
        sysAttachment.setCreateBy(loginUserVo.getId()==null?null:loginUserVo.getId());
        sysAttachment.setCreateTime(Calendar.getInstance().getTime());
        sysAttachment.setFileExt(FileUtils.getFileExt(fileName));
        sysAttachment.setFileNameWithExt(fileName);
        sysAttachment.setFilePath(SysContants.FILE_UPLOAD_LOCATION + newFileName);
        sysAttachment.setFileSize(((Long)file.getSize()).intValue());
        sysAttachmentService.insert(sysAttachment);

        return Result.ok(sysAttachment);
    }

    @RequestMapping(path = "captcha.jpg", method = RequestMethod.GET)
    public ModelAndView getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        //生成验证码文本
        String capText = kaptcha.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        System.out.println("生成验证码文本====" + capText);
        //利用生成的字符串构建图片
        BufferedImage bi = kaptcha.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    /**
     * 检测登录名是否重复
     * @param loginName
     * @return
     */
    @RequestMapping("/checkUserCode")
    @ResponseBody
    public Boolean checkUserCode(String loginName){
        SysUser sysUser = userService.findByLoginUsername(loginName);
        if(sysUser==null){
            return true;
        }
        return false;
    }
}
